<template>
  <div class="smart-school-log-container">
    <h2>🎓 智能学校登录</h2>

    <div v-if="currentStep === 'guide'" class="guide-step">
      <div class="feature-intro">
        <h3>✨ 更简单的登录方式</h3>
        <p>
          我们为您提供了更便捷的登录体验，只需输入学号和密码，系统将自动完成登录和数据同步。
        </p>
      </div>

      <div class="method-cards">
        <div class="method-card" @click="selectMethod('auto')">
          <div class="card-icon">🚀</div>
          <h4>自动登录模式</h4>
          <p>输入学号密码，系统自动登录并获取课表</p>
          <span class="card-tag recommended">推荐</span>
        </div>

        <div class="method-card" @click="selectMethod('manual')">
          <div class="card-icon">🔧</div>
          <h4>手动Cookie模式</h4>
          <p>手动获取Cookie并粘贴（适合技术用户）</p>
          <span class="card-tag">备用方案</span>
        </div>
      </div>
    </div>

    <div v-if="currentStep === 'auto'" class="auto-step">
      <div class="back-btn" @click="goBack">
        <el-icon><ArrowLeft /></el-icon> 返回选择
      </div>

      <div class="form-container">
        <h3>🔐 学校账号登录</h3>
        <p class="security-note">
          <el-icon><Lock /></el-icon>
          您的账号信息仅用于获取课表数据，不会被存储
        </p>

        <el-form
          :model="loginForm"
          :rules="rules"
          ref="formRef"
          label-width="80px"
        >
          <el-form-item label="学号" prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入您的学号"
              :prefix-icon="User"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入您的密码"
              :prefix-icon="Lock"
              show-password
            /> </el-form-item
          >>

          <el-form-item>
            <el-button
              type="primary"
              @click="autoLogin"
              :loading="loading"
              size="large"
              style="width: 100%"
            >
              <span v-if="!loading">立即登录并同步课表</span>
              <span v-else>{{ loadingText }}</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div v-if="currentStep === 'manual'" class="manual-step">
      <div class="back-btn" @click="goBack">
        <el-icon><ArrowLeft /></el-icon> 返回选择
      </div>

      <div class="manual-container">
        <h3>📋 手动Cookie获取</h3>
        <div class="step-guide">
          <el-steps :active="manualStep" finish-status="success">
            <el-step title="打开登录页" description="在新窗口中登录" />
            <el-step title="获取Cookie" description="按F12复制Cookie" />
            <el-step title="提交数据" description="粘贴并提交" />
          </el-steps>
        </div>

        <div v-if="manualStep === 0" class="step-content">
          <el-button type="primary" @click="openLoginPage">
            打开武汉大学综合理解系统
          </el-button>
          <p class="step-tip">请在新窗口中完成登录，然后点击下一步</p>
          <el-button @click="manualStep = 1">下一步</el-button>
        </div>

        <div v-if="manualStep === 1" class="step-content">
          <div class="cookie-guide">
            <h4>📖 获取Cookie步骤：</h4>
            <ol>
              <li>确保已在新窗口中登录成功</li>
              <li>按 <kbd>F12</kbd> 打开开发者工具</li>
              <li>切换到 <b>Network</b> 选项卡</li>
              <li>刷新页面，找到任一请求</li>
              <li>在 Headers → Request Headers → Cookie 中复制完整值</li>
            </ol>
          </div>
          <el-button @click="manualStep = 2">我已获取到Cookie</el-button>
        </div>

        <div v-if="manualStep === 2" class="step-content">
          <el-input
            v-model="manualCookie"
            type="textarea"
            :rows="4"
            placeholder="请粘贴完整的Cookie内容"
          />
          <el-button
            type="success"
            @click="submitManualCookie"
            :loading="loading"
            :disabled="!manualCookie"
          >
            提交Cookie
          </el-button>
        </div>
      </div>
    </div>

    <div v-if="currentStep === 'success'" class="success-step">
      <el-result
        icon="success"
        title="登录成功！"
        sub-title="课表数据已成功同步到您的账户"
      >
        <template #extra>
          <el-button type="primary" @click="goToSchedule">
            <el-icon><Calendar /></el-icon>
            查看我的课表
          </el-button>
          <el-button @click="resetFlow">再次同步</el-button>
        </template>
      </el-result>
    </div>

    <div v-if="currentStep === 'error'" class="error-step">
      <el-result icon="error" title="登录失败" :sub-title="errorMessage">
        <template #extra>
          <el-button type="primary" @click="goBack">重新尝试</el-button>
          <el-button @click="selectMethod('manual')">切换到手动模式</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock, ArrowLeft, Calendar } from "@element-plus/icons-vue";
import { handleCookie, autoCurriculum } from "../../api/school";
import { useUserStore } from "../../stores/user";

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const currentStep = ref<"guide" | "auto" | "manual" | "success" | "error">(
  "guide"
);
const loading = ref(false);
const loadingText = ref("正在登录...");
const errorMessage = ref("");
const manualStep = ref(0);
const manualCookie = ref("");

// 表单数据
const loginForm = reactive({
  username: "",
  password: "",
  userid: 1, // 默认用户ID，实际应该从登录状态获取
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 8, max: 20, message: "学号长度应在8-20位之间", trigger: "blur" },
  ],
  userid: [
    { required: true, message: "请输入用户ID", trigger: "blur" },
    { type: "number", min: 1, message: "用户ID必须大于0", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
};

const formRef = ref();

// 方法选择
const selectMethod = (method: "auto" | "manual") => {
  currentStep.value = method;
  if (method === "manual") {
    manualStep.value = 0;
  }
};

// 返回选择页面
const goBack = () => {
  currentStep.value = "guide";
  resetForm();
};

// 重置表单
const resetForm = () => {
  loginForm.username = "";
  loginForm.password = "";
  loginForm.userid = Number(userStore.id);
  manualCookie.value = "";
  manualStep.value = 0;
  loading.value = false;
  errorMessage.value = "";
};

// 自动登录
const autoLogin = async () => {
  try {
    // 表单验证
    await formRef.value?.validate();

    loading.value = true;
    loadingText.value = "正在连接学校系统...";

    // 增加超时控制（30秒）
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error("请求超时，请稍后重试")), 1200000);
    });
    // 调用后端自动登录接口
    const result = await Promise.race([
      autoCurriculum({
        username: loginForm.username,
        userid: Number(userStore.id), // 使用用户ID
        password: loginForm.password,
        date: new Date().toISOString().split("T")[0],
      }),
      timeoutPromise,
    ]);

    // 类型保护，只有 result 是对象且有 success 字段时才处理
    if (typeof result === "object" && result !== null && "success" in result) {
      const response = result as { success: boolean; message?: string };
      if (response.success) {
        loadingText.value = "登录成功，正在同步课表数据...";
        setTimeout(() => {
          currentStep.value = "success";
          loading.value = false;
          ElMessage.success("课表同步成功！");
        }, 1500);
      } else {
        throw new Error(response.message || "登录失败");
      }
    } else {
      throw result; // 直接抛出超时等异常
    }
  } catch (error: any) {
    loading.value = false;
    currentStep.value = "error";
    errorMessage.value = error.message || "网络连接失败，请检查您的网络设置";
    ElMessage.error(errorMessage.value);
  }
};

// 打开登录页面
const openLoginPage = () => {
  window.open("https://zhlj.whu.edu.cn/pc/index", "_blank");
};

// 提交手动Cookie
const submitManualCookie = async () => {
  try {
    loading.value = true;

    const response = await handleCookie({
      cookie: manualCookie.value,
    });

    if (response.success) {
      currentStep.value = "success";
      ElMessage.success("Cookie提交成功，课表同步完成！");
    } else {
      throw new Error(response.message || "提交失败");
    }
  } catch (error: any) {
    currentStep.value = "error";
    errorMessage.value = error.message || "提交失败";
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 前往课表页面
const goToSchedule = () => {
  router.push("/schedule");
};

// 重置流程
const resetFlow = () => {
  resetForm();
  currentStep.value = "guide";
};
</script>

<style scoped>
.smart-school-log-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 24px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

h2 {
  text-align: center;
  color: #1890ff;
  margin-bottom: 32px;
  font-size: 28px;
}

/* 功能介绍 */
.feature-intro {
  text-align: center;
  margin-bottom: 32px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
}

.feature-intro h3 {
  margin-bottom: 8px;
  font-size: 22px;
}

/* 方法卡片 */
.method-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.method-card {
  padding: 24px;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.method-card:hover {
  border-color: #1890ff;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(24, 144, 255, 0.15);
}

.card-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.card-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
}

.card-tag.recommended {
  background: #52c41a;
}

.card-tag:not(.recommended) {
  background: #faad14;
}

/* 返回按钮 */
.back-btn {
  display: inline-flex;
  align-items: center;
  color: #1890ff;
  cursor: pointer;
  margin-bottom: 20px;
  font-size: 14px;
}

.back-btn:hover {
  color: #40a9ff;
}

/* 表单容器 */
.form-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 32px;
  background: #fafafa;
  border-radius: 12px;
}

.security-note {
  display: flex;
  align-items: center;
  color: #52c41a;
  font-size: 14px;
  margin-bottom: 24px;
  padding: 12px;
  background: #f6ffed;
  border-radius: 6px;
}

.security-note .el-icon {
  margin-right: 8px;
}

/* 手动步骤 */
.manual-container {
  max-width: 600px;
  margin: 0 auto;
}

.step-guide {
  margin: 24px 0;
}

.step-content {
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  text-align: center;
}

.step-tip {
  color: #666;
  margin: 16px 0;
}

.cookie-guide {
  text-align: left;
  margin-bottom: 20px;
}

.cookie-guide ol {
  padding-left: 20px;
}

.cookie-guide li {
  margin: 8px 0;
  color: #333;
}

kbd {
  background: #f1f1f1;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 2px 4px;
  font-size: 12px;
}

/* 响应式 */
@media (max-width: 768px) {
  .method-cards {
    grid-template-columns: 1fr;
  }

  .smart-school-log-container {
    margin: 10px;
    padding: 16px;
  }
}

.el-form-item__content {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
